package com.spzx.common.rabbit.service;

import com.alibaba.fastjson2.JSON;
import com.spzx.common.rabbit.entity.GuiguCorrelationData;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class RabbitService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送消息
     *
     * @param exchange   交换机
     * @param routingKey 路由键
     * @param message    消息
     */
    public boolean sendMessage(String exchange, String routingKey, Object message) {
        //1.定义关联数据
        GuiguCorrelationData correlationData = new GuiguCorrelationData();
        String uuid = "mq:" + UUID.randomUUID().toString().replaceAll("-", "");
        correlationData.setId(uuid); //关联数据的id
        correlationData.setMessage(message);
        correlationData.setExchange(exchange);
        correlationData.setRoutingKey(routingKey);


        //3.将关联数据保存到redis缓存中，便于重发消息
        redisTemplate.opsForValue().set(uuid, JSON.toJSONString(correlationData),10, TimeUnit.MINUTES);

        //2.发送消息时携带关联数据
        rabbitTemplate.convertAndSend(exchange, routingKey, message,correlationData);


        return true;
    }

    /**
     * 发送延迟消息：利用延迟交换机
     * @param exchangeDelay 交换机名称
     * @param routingDelay 路由key
     * @param message 消息
     * @param delayTime 延迟时间
     * @return 是否发送成功
     */
    public boolean sendDelayMessage(String exchangeDelay, String routingDelay, Object message, int delayTime) {
        //1.定义关联数据
        GuiguCorrelationData correlationData = new GuiguCorrelationData();
        String uuid = "mq:" + UUID.randomUUID().toString().replaceAll("-", "");
        correlationData.setId(uuid); //关联数据的id
        correlationData.setMessage(message);
        correlationData.setExchange(exchangeDelay);
        correlationData.setRoutingKey(routingDelay);
        correlationData.setDelay(true); //是延迟消息
        correlationData.setDelayTime(10); //延迟时间：单位按秒


        //3.将关联数据保存到redis缓存中，便于重发消息
        redisTemplate.opsForValue().set(uuid, JSON.toJSONString(correlationData),10, TimeUnit.MINUTES);

        //2.发送消息时携带关联数据
        rabbitTemplate.convertAndSend(exchangeDelay, routingDelay, message,new MessagePostProcessor(){
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                message.getMessageProperties().setDelay(delayTime*1000); //单位毫秒
                return message;
            }
        },correlationData);

        return true;
    }
}